package v1

import (
	"archive/zip"
	"database/sql"
	"errors"
	"fmt"
	"io"
	"math/big"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/hay-kot/httpkit/errchain"
	"github.com/hay-kot/httpkit/server"
	"github.com/rs/zerolog/log"
	"github.com/sysadminsmedia/homebox/backend/internal/core/services"
	"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
	"github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
	"github.com/sysadminsmedia/homebox/backend/internal/web/adapters"
	"gocloud.dev/blob"
	_ "gocloud.dev/blob/fileblob"
)

// HandleItemsGetAll godoc
//
//	@Summary	Query All Items
//	@Tags		Items
//	@Produce	json
//	@Param		q			query		string		false	"search string"
//	@Param		page		query		int			false	"page number"
//	@Param		pageSize	query		int			false	"items per page"
//	@Param		labels		query		[]string	false	"label Ids"		collectionFormat(multi)
//	@Param		locations	query		[]string	false	"location Ids"	collectionFormat(multi)
//	@Param		parentIds	query		[]string	false	"parent Ids"	collectionFormat(multi)
//	@Success	200			{object}	repo.PaginationResult[repo.ItemSummary]{}
//	@Router		/v1/items [GET]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemsGetAll() errchain.HandlerFunc {
	extractQuery := func(r *http.Request) repo.ItemQuery {
		params := r.URL.Query()

		filterFieldItems := func(raw []string) []repo.FieldQuery {
			var items []repo.FieldQuery

			for _, v := range raw {
				parts := strings.SplitN(v, "=", 2)
				if len(parts) == 2 {
					items = append(items, repo.FieldQuery{
						Name:  parts[0],
						Value: parts[1],
					})
				}
			}

			return items
		}

		v := repo.ItemQuery{
			Page:             queryIntOrNegativeOne(params.Get("page")),
			PageSize:         queryIntOrNegativeOne(params.Get("pageSize")),
			Search:           params.Get("q"),
			LocationIDs:      queryUUIDList(params, "locations"),
			LabelIDs:         queryUUIDList(params, "labels"),
			NegateLabels:     queryBool(params.Get("negateLabels")),
			OnlyWithoutPhoto: queryBool(params.Get("onlyWithoutPhoto")),
			OnlyWithPhoto:    queryBool(params.Get("onlyWithPhoto")),
			ParentItemIDs:    queryUUIDList(params, "parentIds"),
			IncludeArchived:  queryBool(params.Get("includeArchived")),
			Fields:           filterFieldItems(params["fields"]),
			OrderBy:          params.Get("orderBy"),
		}

		if strings.HasPrefix(v.Search, "#") {
			aidStr := strings.TrimPrefix(v.Search, "#")

			aid, ok := repo.ParseAssetID(aidStr)
			if ok {
				v.Search = ""
				v.AssetID = aid
			}
		}

		return v
	}

	return func(w http.ResponseWriter, r *http.Request) error {
		ctx := services.NewContext(r.Context())

		items, err := ctrl.repo.Items.QueryByGroup(ctx, ctx.GID, extractQuery(r))
		totalPrice := new(big.Int)
		for _, item := range items.Items {
			if !item.SoldTime.IsZero() { // Skip items with a non-null SoldDate
				continue
			}
			totalPrice.Add(totalPrice, big.NewInt(int64(item.PurchasePrice*100)))
		}

		totalPriceFloat := new(big.Float).SetInt(totalPrice)
		totalPriceFloat.Quo(totalPriceFloat, big.NewFloat(100))

		if err != nil {
			if errors.Is(err, sql.ErrNoRows) {
				return server.JSON(w, http.StatusOK, repo.PaginationResult[repo.ItemSummary]{
					Items: []repo.ItemSummary{},
				})
			}
			log.Err(err).Msg("failed to get items")
			return validate.NewRequestError(err, http.StatusInternalServerError)
		}
		return server.JSON(w, http.StatusOK, items)
	}
}

// HandleItemFullPath godoc
//
//	@Summary	Get the full path of an item
//	@Tags		Items
//	@Produce	json
//	@Param		id	path		string	true	"Item ID"
//	@Success	200	{object}	[]repo.ItemPath
//	@Router		/v1/items/{id}/path [GET]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemFullPath() errchain.HandlerFunc {
	fn := func(r *http.Request, ID uuid.UUID) ([]repo.ItemPath, error) {
		auth := services.NewContext(r.Context())
		item, err := ctrl.repo.Items.GetOneByGroup(auth, auth.GID, ID)
		if err != nil {
			return nil, err
		}

		paths, err := ctrl.repo.Locations.PathForLoc(auth, auth.GID, item.Location.ID)
		if err != nil {
			return nil, err
		}

		if item.Parent != nil {
			paths = append(paths, repo.ItemPath{
				Type: repo.ItemTypeItem,
				ID:   item.Parent.ID,
				Name: item.Parent.Name,
			})
		}

		paths = append(paths, repo.ItemPath{
			Type: repo.ItemTypeItem,
			ID:   item.ID,
			Name: item.Name,
		})

		return paths, nil
	}

	return adapters.CommandID("id", fn, http.StatusOK)
}

// HandleItemsCreate godoc
//
//	@Summary	Create Item
//	@Tags		Items
//	@Produce	json
//	@Param		payload	body		repo.ItemCreate	true	"Item Data"
//	@Success	201		{object}	repo.ItemSummary
//	@Router		/v1/items [POST]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemsCreate() errchain.HandlerFunc {
	fn := func(r *http.Request, body repo.ItemCreate) (repo.ItemOut, error) {
		return ctrl.svc.Items.Create(services.NewContext(r.Context()), body)
	}

	return adapters.Action(fn, http.StatusCreated)
}

// HandleItemGet godocs
//
//	@Summary	Get Item
//	@Tags		Items
//	@Produce	json
//	@Param		id	path		string	true	"Item ID"
//	@Success	200	{object}	repo.ItemOut
//	@Router		/v1/items/{id} [GET]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemGet() errchain.HandlerFunc {
	fn := func(r *http.Request, ID uuid.UUID) (repo.ItemOut, error) {
		auth := services.NewContext(r.Context())

		return ctrl.repo.Items.GetOneByGroup(auth, auth.GID, ID)
	}

	return adapters.CommandID("id", fn, http.StatusOK)
}

// HandleItemDelete godocs
//
//	@Summary	Delete Item
//	@Tags		Items
//	@Produce	json
//	@Param		id	path	string	true	"Item ID"
//	@Success	204
//	@Router		/v1/items/{id} [DELETE]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemDelete() errchain.HandlerFunc {
	fn := func(r *http.Request, ID uuid.UUID) (any, error) {
		auth := services.NewContext(r.Context())
		err := ctrl.repo.Items.DeleteByGroup(auth, auth.GID, ID)
		return nil, err
	}

	return adapters.CommandID("id", fn, http.StatusNoContent)
}

// HandleItemUpdate godocs
//
//	@Summary	Update Item
//	@Tags		Items
//	@Produce	json
//	@Param		id		path		string			true	"Item ID"
//	@Param		payload	body		repo.ItemUpdate	true	"Item Data"
//	@Success	200		{object}	repo.ItemOut
//	@Router		/v1/items/{id} [PUT]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemUpdate() errchain.HandlerFunc {
	fn := func(r *http.Request, ID uuid.UUID, body repo.ItemUpdate) (repo.ItemOut, error) {
		auth := services.NewContext(r.Context())

		body.ID = ID
		return ctrl.repo.Items.UpdateByGroup(auth, auth.GID, body)
	}

	return adapters.ActionID("id", fn, http.StatusOK)
}

// HandleItemPatch godocs
//
//	@Summary	Update Item
//	@Tags		Items
//	@Produce	json
//	@Param		id		path		string			true	"Item ID"
//	@Param		payload	body		repo.ItemPatch	true	"Item Data"
//	@Success	200		{object}	repo.ItemOut
//	@Router		/v1/items/{id} [Patch]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemPatch() errchain.HandlerFunc {
	fn := func(r *http.Request, ID uuid.UUID, body repo.ItemPatch) (repo.ItemOut, error) {
		auth := services.NewContext(r.Context())

		body.ID = ID
		err := ctrl.repo.Items.Patch(auth, auth.GID, ID, body)
		if err != nil {
			return repo.ItemOut{}, err
		}

		return ctrl.repo.Items.GetOneByGroup(auth, auth.GID, ID)
	}

	return adapters.ActionID("id", fn, http.StatusOK)
}

// HandleGetAllCustomFieldNames godocs
//
//	@Summary	Get All Custom Field Names
//	@Tags		Items
//	@Produce	json
//	@Success	200
//	@Router		/v1/items/fields [GET]
//	@Success	200	{object}	[]string
//	@Security	Bearer
func (ctrl *V1Controller) HandleGetAllCustomFieldNames() errchain.HandlerFunc {
	fn := func(r *http.Request) ([]string, error) {
		auth := services.NewContext(r.Context())
		return ctrl.repo.Items.GetAllCustomFieldNames(auth, auth.GID)
	}

	return adapters.Command(fn, http.StatusOK)
}

// HandleGetAllCustomFieldValues godocs
//
//	@Summary	Get All Custom Field Values
//	@Tags		Items
//	@Produce	json
//	@Success	200
//	@Router		/v1/items/fields/values [GET]
//	@Success	200	{object}	[]string
//	@Security	Bearer
func (ctrl *V1Controller) HandleGetAllCustomFieldValues() errchain.HandlerFunc {
	type query struct {
		Field string `schema:"field" validate:"required"`
	}

	fn := func(r *http.Request, q query) ([]string, error) {
		auth := services.NewContext(r.Context())
		return ctrl.repo.Items.GetAllCustomFieldValues(auth, auth.GID, q.Field)
	}

	return adapters.Query(fn, http.StatusOK)
}

// HandleItemsAttachmentsExport godocs
//
//	@Summary	Export All Attachments as ZIP
//	@Tags		Items Attachments
//	@Success	200	{string}	string	"application/zip"
//	@Router		/v1/items/attachments/export [GET]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemsAttachmentsExport() errchain.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) error {
		ctx := services.NewContext(r.Context())

		// 打开存储桶
		bucket, err := blob.OpenBucket(ctx, ctrl.repo.Attachments.GetConnString())
		if err != nil {
			log.Err(err).Msg("failed to open bucket")
			return validate.NewRequestError(err, http.StatusInternalServerError)
		}
		defer bucket.Close()

		// 设置响应头
		timestamp := time.Now().Format("2006-01-02_15-04-05")
		filename := fmt.Sprintf("homebox-attachments_%s.zip", timestamp)
		w.Header().Set("Content-Type", "application/zip")
		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))

		// 创建 ZIP 文件
		zipWriter := zip.NewWriter(w)
		defer zipWriter.Close()

		// 遍历 attachments 文件夹中的所有文件
		iter := bucket.List(&blob.ListOptions{
			Prefix: "attachments/",
		})

		fileCount := 0
		for {
			obj, err := iter.Next(ctx)
			if err == io.EOF {
				break
			}
			if err != nil {
				log.Err(err).Msg("failed to iterate files")
				return validate.NewRequestError(err, http.StatusInternalServerError)
			}

			// 跳过目录
			if strings.HasSuffix(obj.Key, "/") {
				continue
			}

			// 从存储桶读取文件
			file, err := bucket.NewReader(ctx, obj.Key, nil)
			if err != nil {
				log.Warn().Err(err).Str("path", obj.Key).Msg("failed to open file from storage, skipping")
				continue
			}

			// 使用原始文件名（去掉 attachments/ 前缀）
			originalFileName := strings.TrimPrefix(obj.Key, "attachments/")
			
			// 在ZIP中创建文件条目
			zipFile, err := zipWriter.Create(originalFileName)
			if err != nil {
				log.Warn().Err(err).Str("file", originalFileName).Msg("failed to create zip entry, skipping")
				file.Close()
				continue
			}

			// 复制文件内容到 ZIP
			_, err = io.Copy(zipFile, file)
			file.Close()
			if err != nil {
				log.Warn().Err(err).Str("file", originalFileName).Msg("failed to copy file to zip, skipping")
				continue
			}

			fileCount++
		}

		if fileCount == 0 {
			return server.JSON(w, http.StatusOK, map[string]string{"message": "no files found in attachments folder"})
		}

		log.Info().Int("file_count", fileCount).Msg("exported attachments")
		return nil
	}
}

// HandleItemsAttachmentsImport godocs
//
//	@Summary	Import Attachments from ZIP
//	@Tags		Items Attachments
//	@Accept		multipart/form-data
//	@Produce	json
//	@Success	200	{object}	map[string]string
//	@Param		file	formData	file	true	"ZIP file to upload"
//	@Router		/v1/items/attachments/import [POST]
//	@Security	Bearer
func (ctrl *V1Controller) HandleItemsAttachmentsImport() errchain.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) error {
		err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
		if err != nil {
			log.Err(err).Msg("failed to parse multipart form")
			return validate.NewRequestError(err, http.StatusBadRequest)
		}

		file, _, err := r.FormFile("file")
		if err != nil {
			log.Err(err).Msg("failed to get file from form")
			return validate.NewRequestError(err, http.StatusBadRequest)
		}
		defer file.Close()

		// 创建临时文件保存上传的 ZIP
		tempFile, err := os.CreateTemp("", "attachments-*.zip")
		if err != nil {
			log.Err(err).Msg("failed to create temp file")
			return validate.NewRequestError(err, http.StatusInternalServerError)
		}
		defer func() {
			tempFile.Close()
			os.Remove(tempFile.Name())
		}()

		// 将上传的文件保存到临时文件
		_, err = io.Copy(tempFile, file)
		if err != nil {
			log.Err(err).Msg("failed to save uploaded file")
			return validate.NewRequestError(err, http.StatusInternalServerError)
		}

		// 重新打开临时文件用于读取
		tempFile.Seek(0, 0)

		// 解压 ZIP 文件
		zipReader, err := zip.OpenReader(tempFile.Name())
		if err != nil {
			log.Err(err).Msg("failed to open zip file")
			return validate.NewRequestError(err, http.StatusBadRequest)
		}
		defer zipReader.Close()

		importedCount := 0
		attachmentsDir := "attachments"

		// 确保 attachments 目录存在
		if err := os.MkdirAll(attachmentsDir, 0755); err != nil {
			log.Err(err).Msg("failed to create attachments directory")
			return validate.NewRequestError(err, http.StatusInternalServerError)
		}

		// 处理 ZIP 中的每个文件
		for _, zipFile := range zipReader.File {
			if zipFile.FileInfo().IsDir() {
				continue
			}

			// 打开 ZIP 中的文件
			srcFile, err := zipFile.Open()
			if err != nil {
				log.Warn().Err(err).Str("file", zipFile.Name).Msg("failed to open file in zip, skipping")
				continue
			}

			// 使用原始文件名，保持与导出时一致
			originalFileName := filepath.Base(zipFile.Name)
			
			// 在 attachments 目录中创建相同的文件名
			destPath := filepath.Join(attachmentsDir, originalFileName)
			
			// 记录导入信息
			log.Info().Str("original_name", originalFileName).Str("dest_path", destPath).Msg("importing attachment file")

			// 创建目标文件
			destFile, err := os.Create(destPath)
			if err != nil {
				log.Warn().Err(err).Str("file", destPath).Msg("failed to create destination file, skipping")
				srcFile.Close()
				continue
			}

			// 复制文件内容
			_, err = io.Copy(destFile, srcFile)
			srcFile.Close()
			destFile.Close()

			if err != nil {
				log.Warn().Err(err).Str("file", destPath).Msg("failed to copy file, skipping")
				os.Remove(destPath)
				continue
			}

			importedCount++
		}

		return server.JSON(w, http.StatusOK, map[string]interface{}{
			"message":    fmt.Sprintf("Successfully imported %d attachments", importedCount),
			"imported":   importedCount,
			"totalFiles": len(zipReader.File),
		})
	}
}

// HandleClearInventory godocs
//
//	@Summary	Clear All Inventory Items
//	@Tags		Items
//	@Produce	json
//	@Success	200	{object}	map[string]int	"{\"deleted\": 0}"
//	@Router		/v1/items/clear [DELETE]
//	@Security	Bearer
func (ctrl *V1Controller) HandleClearInventory() errchain.HandlerFunc {
	fn := func(r *http.Request) (map[string]int, error) {
		auth := services.NewContext(r.Context())

		deletedCount, err := ctrl.svc.Items.ClearInventory(r.Context(), auth.GID)
		if err != nil {
			return nil, err
		}

		return map[string]int{"deleted": deletedCount}, nil
	}

	return adapters.Command(fn, http.StatusOK)
}
